"""
Steam交易状态刷新接口模块
"""
import json
import logging
import requests
from typing import Optional
from reqapi.api import BaseApi
from reqapi.models.steam_trade_status_refresh import (
    SteamTradeStatusRefreshRequest, SteamTradeStatusRefreshResponse
)

logger = logging.getLogger(__name__)

class SteamTradeStatusRefreshApi(BaseApi):
    """Steam交易状态刷新接口"""
    
    def __init__(self, device_id: str = None, device_token: str = None, 
                 auth_token: str = "", uk: str = ""):
        """初始化Steam交易状态刷新接口
        
        Args:
            device_id: 设备ID
            device_token: 设备令牌，如果不传则使用device_id
            auth_token: 授权令牌
            uk: uk值
        """
        device_token = device_token or device_id
        super().__init__(device_token, device_id, auth_token, uk)
        
    def refresh(self) -> Optional[SteamTradeStatusRefreshResponse]:
        """刷新Steam交易状态

        Returns:
            Optional[SteamTradeStatusRefreshResponse]: 交易状态响应，如果请求失败则返回None
        """
        try:
            # 构造请求数据
            request = SteamTradeStatusRefreshRequest(
                Sessionid=self.device_id
            )
            data = request.to_dict()
            # 获取基础请求头
            headers = self.common_headers.copy()
            headers.update({
                "content-length": str(len(json.dumps(data)))
            })
            print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
            print(f"请求数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
            # 统一用拦截器处理请求和响应
            url = f"{self.BASE_URL}/api/youpin/bff/UserSteam/user/steam/trade/status/refresh"
            response = self.interceptor.send_request(
                url,
                json=data,
                headers=headers,
                need_encrypt=False
            )
            # 兼容返回dict或response对象
            if isinstance(response, dict):
                response_json = response
            elif hasattr(response, 'json'):
                response_json = response.json()
            else:
                response_json = response
            print(f"响应内容: {json.dumps(response_json, indent=2, ensure_ascii=False)}")
            return SteamTradeStatusRefreshResponse.from_dict(response_json)
        except Exception as e:
            logger.error(f"刷新Steam交易状态时发生错误: {str(e)}")
            return None


if __name__ == "__main__":
    # 测试刷新Steam交易状态
    from com.db.order_account_manager import OrderAccountManager
    account_manager = OrderAccountManager()
    account = account_manager.get_account_by_id(1)
            
    if not account:
        print("无法获取ID为1的账号")
        import sys
        sys.exit(1)
            
    device_id = account.get('device_id', '')
    auth_token = account.get('uu_token', '')
    uk = account.get('uk', '')
    
    api = SteamTradeStatusRefreshApi(device_id=device_id, auth_token=auth_token, uk=uk)
    result = api.refresh()
    
    if result:
        print(f"刷新Steam交易状态成功: {result.msg}")
        if result.data:
            print(f"交易状态: {result.data.steamTradeStatusTip}")
            print(f"用户ID: {result.data.userId}")
            print(f"Steam交易状态: {result.data.steamTradeStatus}")
            if result.data.steamJumpUrl:
                print(f"Steam跳转URL: {result.data.steamJumpUrl}")
    else:
        print("刷新Steam交易状态失败")
